#!/usr/bin/python3
import os, sys, json

#python3 extract_origin_data.py
symbol = 'UCLA'
# 项目地址
project_dir = '/mri_projects/ASD_Analysis'
# rest 文件
rest_dir = os.path.join(project_dir, "Origin/rest/")
list_dirs = os.listdir(rest_dir)
list_symbol_dirs = [dir_item for dir_item in list_dirs if symbol in dir_item]

subj_dir = os.path.join(rest_dir, list_symbol_dirs[0])
rest_sub_dir = os.path.join(subj_dir, os.listdir(subj_dir)[0])
rest_nii_file = os.path.join(rest_sub_dir, os.listdir(rest_sub_dir)[0])
# 时间片长度
slice_number = os.popen("mri_info " + rest_nii_file + " --nslices")
slice_number = int(slice_number.readlines()[0])
# 目标文件地址
target_file_path = os.path.join(project_dir, "Lists")

dir_t1 = 'T1'
dir_rest = 'rest'

def get_slice_order(slice_number):
    odd_list = []
    even_list = []

    for order_item in range(1, slice_number + 1):
        if order_item % 2 == 0:
            even_list.append(order_item)
        else:
            odd_list.append(order_item)

    slice_list = []
    slice_list.extend(odd_list)
    slice_list.extend(even_list)

    return slice_list

def write_slice_order(lists_path, slice_file_name, slice_list):
    full_file_path = os.path.join(lists_path, slice_file_name + ".txt")

    slice_list = [str(so_item) for so_item in slice_list]

    print("[Slice Order]: Writing slice order in file `%s`" % (full_file_path))
    print("[Slice Order]: [%s]" % (",".join(slice_list)))

    fp = open(full_file_path, "w")
    for order_item in slice_list:
        fp.write(order_item + "\n")
    fp.close()

    print("[Slice Order]: Writing slice order done!")

    return full_file_path

slice_list = get_slice_order(slice_number)
write_slice_order(target_file_path, "slice_order_"+symbol, slice_list)
